//
//  MCOrderListViewController.swift
//  StoreManage
//
//  Created by MC on 2017/12/20.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

typealias MCOrderListViewControllerClosure = (UIViewController) -> Void

class MCOrderListViewController: MCViewController {
    
    public var status : Int = 0  // 0全部，2待发货，3待收货，4已完成（核销页面传0）
    
    public var activityLogId = 0  // 活动分销记录Id 可选
    
    public var writeOffStatus = 0 // 1未核销；2已核销；3快递送（核销统计传参）
    
    public var isSbuVC = 0        // 页面跳转的时候用到
    
    private var pageNumber = 1

    public var closure : MCOrderListViewControllerClosure?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        pageNumber = 1
        sendNetworking()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
    }
    
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.grouped)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
}



//MARK: 通知回调，闭包回调，点击事件
extension MCOrderListViewController {
    @objc func rightItemClicked() {
        let vc = MCOrderSearchViewController()
        vc.status = status
        vc.activityLogId = activityLogId
        vc.writeOffStatus = writeOffStatus
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
}


//MARK: 网络请求
extension MCOrderListViewController {
    
    func sendNetworking() {
        
        let para = [
            "storeId" : MCUserinfo_getStoreId(),
            "status"  : status,
            "pageNum" : pageNumber,
            "activityLogId" : activityLogId,
            "writeOffStatus" : writeOffStatus
            ] as [String : Any]
        
        
        MCNetwork.POST(JAVA_getStoreOrderList, para, vc: self, success: { (data) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            if self.pageNumber == 1 {
                self.tableView.mj_footer.resetNoMoreData()
                self.dataArrayM.removeAllObjects()
            }
            
            let dataDict = data.dictionaryObject ?? [:]
            let array = dataDict["list"] as! NSArray
            
            if array.count + self.dataArrayM.count == 0 {
                self.tableView.showBgImage()
            } else {
                self.tableView.hideBgImage()
                
                if array.count == 0 {
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                }
                
                for dict in array {
                    let fatherModel = MCOrderListFatherModel()
                    fatherModel.setValuesForKeys(dict as! [String : Any])
                    self.dataArrayM.add(fatherModel)
                }
                self.tableView.reloadData()
            }

            
        }, failure: nil)
    }
}

//MARK: UI的处理,通知的接收
extension MCOrderListViewController {
    func baseSetting() {
        self.title = "订单"
        self.view.backgroundColor = UIColor.white
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_image(#imageLiteral(resourceName: "Reuse_search"), target: self, selector: #selector(rightItemClicked))
    
        
        tableView.mj_header = MCRefreshHeader.init(refreshingBlock: {
            self.pageNumber = 1
            self.sendNetworking()
        })
                
        self.tableView.mj_footer = MCRefreshFooter.init(refreshingBlock: {
            self.pageNumber += 1
            self.sendNetworking()
        })
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, CGFloat(MCSafeAreaBottomHeight), 0))
        }
    }
}






extension MCOrderListViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 55
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = MCOrderListSectionHeaderView()
        view.model = self.dataArrayM[section] as! MCOrderListFatherModel
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 47
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = MCOrderListSectionFooterView()
        view.model = self.dataArrayM[section] as! MCOrderListFatherModel
        return view
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let model = self.dataArrayM[section] as! MCOrderListFatherModel

        return model.listBaOrderDetailVo.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.dataArrayM[indexPath.section] as! MCOrderListFatherModel
        
        let cell = MCOrderListCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        cell.model = model.listBaOrderDetailVo[indexPath.row] as! MCOrderListModel
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      
        let model = self.dataArrayM[indexPath.section] as! MCOrderListFatherModel

        // 分销员只能查看
        if MCUserinfo_getLevel() == MCRole_salesStaff {
            
            let vc = MCOrderDetailShowViewController()
            vc.orderSn = model.orderSn
            self.closure?(vc)
          return
        }
        
        
        switch model.status {
        case 2:
            let vc = MCOrderDetailWaitSendViewController()
            vc.orderSn = model.orderSn
            if isSbuVC == 1 {
                self.closure?(vc)
            } else {
                MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
            }
        case 3:
            let vc = MCOrderDetailWaitPickUpViewController()
            vc.orderSn = model.orderSn
            if isSbuVC == 1 {
                self.closure?(vc)
            } else {
                MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
            }
        case 4:
            let vc = MCOrderDetailCompleteViewController()
            vc.orderSn = model.orderSn
            if isSbuVC == 1 {
                self.closure?(vc)
            } else {
                MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
            }
        case 6:
            let vc = MCOrderDetailSuccessfulDealViewController()
            vc.orderSn = model.orderSn
            if isSbuVC == 1 {
                self.closure?(vc)
            } else {
                MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
            }
        default:
            break
        }
    }
}



